import axios from  'axios'
import router from '@/router'
import store from '@/store'

const HOST = 'http://45.77.125.8:8099/'

// 响应拦截器
axios.interceptors.response.use(
  res => {
    if (res.data.code == 401) {
      store.state.isLogin = false
      localStorage.removeItem('token')
      router.push('/login')
    }
    return res
  },
  err => {
    return Promise.reject(err)
  }
)

export function POST(url, params) {
  let config = {}
  let _url = HOST + url
  let token = localStorage.getItem('token')
  let needToken = params.needToken

  if (needToken == undefined) {
    config.headers = { token }
  }

  return axios.post(_url, params, config).then( res => {
    return Promise.resolve(res.data)
  })
  .catch( err => {
    console.log(err)
  })
}

export function GET(url, params) {
  let headers = {}
  let _url = HOST + url
  let token = localStorage.getItem('token')
  let needToken = params.needToken

  if (needToken == undefined) {
    headers.token = token
  }

  return axios.get(_url, { params, headers} ).then( res => {
    return Promise.resolve(res.data)
  })
  .catch( err => {
    console.log(err)
  })
}

export function DELETE(url, params) {
  let headers = {}
  let _url = HOST + url
  let token = localStorage.getItem('token')
  let needToken = params.needToken

  if (needToken == undefined) {
    headers.token = token
  }
  
  return axios.delete(_url, { params, headers }).then( res => {
    return Promise.resolve(res.data)
  })
  .catch( err => {
    console.log(err)
  })
}